package com.flow.framework.core.validation.validator;

import com.flow.framework.common.exception.ParamCheckedException;
import com.flow.framework.core.validation.annotation.MinDecimalCustomization;
import com.flow.framework.core.validation.validator.base.BaseValidator;

import javax.validation.ConstraintValidatorContext;
import java.math.BigDecimal;

/**
 * DecimalMin校验器
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/1/22
 */
public class MinDecimalValidator extends BaseValidator<MinDecimalCustomization, BigDecimal> {

    private MinDecimalCustomization minDecimalCustomization;

    private String errorMsg;

    @Override
    public void initialize(MinDecimalCustomization minDecimalCustomization) {
        this.minDecimalCustomization = minDecimalCustomization;
        this.errorMsg = "value less than" + minDecimalCustomization.value();
    }

    @Override
    public boolean isValid(BigDecimal value, ConstraintValidatorContext context) {
        if (null == value) {
            return true;
        }

        if (minDecimalCustomization.containsEquals()) {
            if (value.compareTo(new BigDecimal(minDecimalCustomization.value())) < 0) {
                super.logError(context, value, errorMsg);
                throw new ParamCheckedException(minDecimalCustomization.errorCode());
            }
        } else {
            if (value.compareTo(new BigDecimal(minDecimalCustomization.value())) <= 0) {
                super.logError(context, value, errorMsg);
                throw new ParamCheckedException(minDecimalCustomization.errorCode());
            }
        }
        return true;
    }
}
